<template>
    <div class="app-container sorder   ">
        <div v-if="open == !true">
            <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="105px">
                <el-form-item label="申请单号" prop="orderId">
                    <el-input v-model="queryParams.orderId" placeholder="请输入订单ID" clearable size="small" @keyup.enter.native="handleQuery" />
                </el-form-item>

                <el-form-item label="关联订单号" prop="platOrderId">
                    <el-input v-model="queryParams.platOrderId" placeholder="请输入订单ID" clearable size="small" @keyup.enter.native="handleQuery" />
                </el-form-item>

                <el-form-item label="申请类型" prop="orderType">
                    <el-select v-model="queryParams.orderType" placeholder="请选择售后类型 " clearable size="small">
                        <el-option label="补偿" value="0" />
                        <el-option label="仅退款" value="1" />
                        <el-option label="退货退款" value="2" />
                    </el-select>
                </el-form-item>

                <el-form-item label="售后单状态" prop="orderStatus">
                    <el-select v-model="queryParams.orderStatus" placeholder="请选择售后单状态 " clearable size="small">
                        <el-option label="待审核" value="0" />
                        <el-option label="审核拒绝" value="1" />
                        <el-option label="审核通过待发货" value="4" />
                        <el-option label="待收货" value="5" />
                        <el-option label="已收货待确认" value="6" />
                        <el-option label="已完成" value="3" />
                        <el-option label="已取消" value="2" />
                    </el-select>
                </el-form-item>

                <el-form-item label="申请时间" prop="createdTime">
                    <el-date-picker clearable size="small" value-format="yyyy-MM-dd" format="yyyy-MM-dd" style="width: 200px" v-model="queryParams.createdTime" type="date" placeholder="选择申请时间"> </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
                <el-form-item>
                    <!--                    <el-button type="warning" icon="el-icon-download" size="mini" @click="update" v-hasPermi="['biz:sorder:export']">下载模板</el-button>-->
                    <!--                    <el-upload style="display:inline-block;margin-top:4px" ref="dealFile" :action="importAction" :headers="headers"
                    :before-upload="fileBeforeUpload"
                    :on-success="fieldBeforeUpload">-->
                    <!--                        <el-button type="warning" icon="el-icon-upload2" size="mini" v-hasPermi="['biz:order:export']">导入</el-button>-->
                    <!--                    </el-upload>-->
                    <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['biz:sorder:export']">导出</el-button>
                </el-form-item>
            </el-form>
            <!-- 表格 -->
            <el-table @selection-change="handleSelectionChange" :data="sorderList" style="width: 100%">
                <el-table-column type="selection" width="55" align="center"> </el-table-column>
                <el-table-column prop="companyName" label="商品信息" width="400">
                    <template slot-scope="scope">
                        <div v-for="(items, index) in scope.row.goodsDeail" :key="index">
                            <div v-if="items.info" class="tableCont">
                                <img :src="items.info.mainImgUrl" alt />
                                <div class="title" style>
                                    {{ items.info.goodsName }} [品牌] {{ items.info.brandName }} [规格] {{ items.info.spec }}  x
                                    {{ items.goods.goodsNum }}
                                </div>
                                <!-- <div class style="margin-left:5px">
                <el-button class="elbutton" v-if="userId != 4" size="mini" type="text" @click="sopenkuang(2,scope.row.orderId,items.goods.goodsId)">退货退款</el-button>
                <el-button class="elbutton" v-if="userId != 4" size="mini" type="text" @click="sopenkuang(3,scope.row.orderId,items.goods.goodsId)">仅退款</el-button>
                <el-button class="elbutton" v-if="userId != 4" size="mini" type="text" @click="sopenkuang(1,scope.row.orderId,items.goods.goodsId)">补偿</el-button>
              </div> -->
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="orderId" label="申请单号" width="130"> </el-table-column>
                <el-table-column prop="platOrderId" label="关联单号" width="130"> </el-table-column>
                <el-table-column fit prop="shop" label="店铺" width="140"> </el-table-column>
                <el-table-column prop="orderType" label="申请类型" width="100"> </el-table-column>
                <el-table-column prop="price" label="退款金额" width="100"> </el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="resonse" label="退款原因" width="100"> </el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="remarks" label="退款说明"> </el-table-column>
                <el-table-column prop="orderStatus" label="操作状态" width="200"> </el-table-column>
                <el-table-column prop="createdTime" label="申请时间" width="100"> </el-table-column>
                <el-table-column label="操作" width="150" fixed="right" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" @click="handleUpdate(scope.row)">查看详情</el-button>
                        <el-button v-if="cisshow && scope.row.orderStatus == '待审核'" style="margin-left: 10px;" size="mini" type="text" icon="el-icon-s-help" @click="tongguo(scope.row, 1)" v-hasPermi="['biz:order:remove']">通过</el-button>

                        <el-button v-if="cisshow && scope.row.orderStatus == '待审核'" style="margin-left: 10px;" size="mini" type="text" icon="el-icon-s-help" @click="tongguo(scope.row, 2)" v-hasPermi="['biz:order:remove']">不通过</el-button>

                        <el-button v-show="cisshow && scope.row.orderStatus == '已收货待确认'" style="margin-left: 10px;" size="mini" type="text" icon="el-icon-s-help" @click="comfirmGet(scope.row)" v-hasPermi="['biz:order:remove']">确认</el-button>

                        <el-button v-show="wuliushow && scope.row.orderStatus == '审核通过待发货'" style="margin-left: 10px;" size="mini" type="text" icon="el-icon-s-help" @click="addWuliu(scope.row)" v-hasPermi="['biz:order:remove']">填写物流信息</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

            <el-dialog title="填写物流单号" :visible.sync="wuliukuang" width="500px">
                <div class="sync">
                    <span>物流公司</span>
                    <el-input class="input" v-model="wuliuInfo.company">请输入内容</el-input>
                </div>
                <div class="sync">
                    <span>物流单号</span>
                    <el-input class="input" v-model="wuliuInfo.bianNo">请输入内容</el-input>
                </div>
                <div style="text-align:center;margin-top:20px">
                    <el-button type="primary" @click="addWt">提交</el-button>
                    <el-button @click="wcancel">取消</el-button>
                </div>
            </el-dialog>
        </div>
        <!-- 详情组件 -->
        <sorderDetails v-if="open == true" @toRetreat="toRetreat" :row="row"></sorderDetails>
        <spreview class="preview" :lists="lists" :hiddens="hiddens" :dialogVisibless="dialogVisibless" :msg="msg" :datas="datas" @showbox="showbox" @showboxs="getList" />
    </div>
</template>

<script>
import { listSorder, getSorder, delSorder, addSorder, updateSorder, exportSorder, submitWuliu, comfirmget, importOrder } from '@/api/biz/sorder';
import sorderDetails from '@/components/sorderDetails/index';
import { getInfo } from '@/api/login';
import { getToken } from '@/utils/auth';
import spreview from '@/components/spreview/index';

export default {
    name: 'Sorder',
    components: {
        sorderDetails,
        spreview
    },
    data() {
        return {
            baseimg: require('../../../assets/image/profile.jpg'),
            row: [],
            isshow: false,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 导入文件服务器地址
            importAction: process.env.VUE_APP_BASE_API + '/after_sale/poiImport',
            headers: {
                Authorization: 'Bearer ' + getToken()
            },
            orderIdList: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 订单表格数据
            sorderList: [],
            // 弹出层标题
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                uid: undefined,
                companyName: undefined,
                orderId: undefined,
                orderType: undefined,
                compensate: undefined,
                orderStatus: undefined,
                platId: undefined,
                plat: undefined,
                shopId: undefined,
                shop: undefined,
                platOrderId: undefined,
                num: undefined,
                price: undefined,
                syncStatus: undefined,
                logisticsCompanyNo: undefined,
                logisticsNo: undefined,
                createdTime: undefined,
                resonse: undefined,
                shopId: this.$store.state.user.shopid,
                sorderId: ''
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                uid: [
                    {
                        required: true,
                        message: '用户id不能为空',
                        trigger: 'blur'
                    }
                ],
                orderId: [
                    {
                        required: true,
                        message: '订单ID不能为空',
                        trigger: 'blur'
                    }
                ]
            },
            // 按钮组
            drawer: false,
            direction: 'ttb',
            userId: '',
            dialogVisible1: false,
            dialogVisible2: false,
            dialogVisible3: false,
            ruleForm: {
                money: '',
                reason: '',
                remarks: ''
            },
            cisshow: false,
            wuliushow: false,
            wuliukuang: false,
            wuliuInfo: {
                company: undefined,
                bianNo: undefined,
                orderId: undefined
            },

            wuliuorderid: '',
            dealFile: [],
            datas: [],
            ishows: false,
            dialogVisibless: false,
            hiddens: false,
            msg: '',
            lists: []
        };
    },
    created() {
        this.getList();

        this.getUrl('/web/getuserrole').then(response => {
            this.getUrl('/web/getuserrole').then(response => {
                if (response.data.roleId == 101) {
                    this.isshow = true;
                    this.cisshow = true;
                } else {
                    this.wuliushow = true;
                }
            });
        });
        // this.userId = 4;
    },
    mounted() {},
    methods: {
        showbox() {
            this.dialogVisibless = false;
            this.hiddens = false;
        },
        comfirmGet(data) {
            this.$confirm('是否 确认 操作?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    comfirmget(data.orderId).then(response => {
                        if (response.code == 200) {
                            this.getList();
                            this.msgSuccess('ok,操作成功！');
                        }
                    });
                })
                .catch(function() {});
        },
        addWt() {
            if (this.wuliuorderid == '') {
                return false;
            }

            if (this.wuliuInfo.company == '') {
                this.msgError('物流公司不能为空');
                return false;
            }

            if (this.wuliuInfo.bianNo == '') {
                this.msgError('物流单号不能为空');
                return false;
            }

            this.wuliuInfo.orderId = this.wuliuorderid;
            submitWuliu(this.wuliuInfo)
                .then(response => {
                    if (response.code == 200) {
                        this.getList();
                        this.msgSuccess('ok,操作成功！');
                        this.wcancel();
                    }
                })
                .catch(() => {
                    // this.msgError('服务异常！');
                });
        },
        wcancel() {
            this.wuliukuang = false;
            this.wuliuInfo.company = '';
            this.wuliuInfo.bianNo = '';
        },

        addWuliu: function(data) {
            this.wuliukuang = true;
            this.wuliuorderid = data.orderId;
        },
        tongguo: function(data, mark) {
            var bj = mark == 1 ? '通过' : '不通过';
            this.$confirm('是否确认执行 审核' + bj + ' 操作?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    this.getUrl('/web/checkSorder/' + data.orderId + '/' + mark).then(response => {
                        if (response.code == 200) {
                            this.getList();
                            this.msgSuccess('ok,操作成功！');
                        }
                    });
                })
                .catch(function() {});
        },

        // 从详情返回
        toRetreat() {
            this.open = false;
        },
        /** 查询订单列表 */
        getList() {
            this.loading = true;
            setTimeout(() => {
                if (localStorage.userId == '4') {
                    listSorder(this.queryParams).then(response => {
                        this.sorderList = response.rows;
                        this.sorderList.forEach(item => {
                            if (item.orderType == 0) {
                                item.orderType = '补偿';
                            } else if (item.orderType == 1) {
                                item.orderType = '仅退款';
                            } else {
                                item.orderType = '退货退款';
                            }
                            //0：已申请，1：审核拒绝，2：已取消, 3: 已完成，4 审核通过待发货，5，待收货
                            if (item.orderStatus == 0) {
                                item.orderStatus = '待审核';
                            } else if (item.orderStatus == 1) {
                                item.orderStatus = '审核拒绝';
                            } else if (item.orderStatus == 2) {
                                item.orderStatus = '已取消';
                            } else if (item.orderStatus == 3) {
                                item.orderStatus = '已完成';
                            } else if (item.orderStatus == 4) {
                                item.orderStatus = '审核通过待发货';
                            } else if (item.orderStatus == 5) {
                                item.orderStatus = '待收货';
                            } else if (item.orderStatus == 6) {
                                item.orderStatus = '已收货待确认';
                            }
                        });
                        this.total = response.total;
                        this.loading = false;
                    });
                } else {
                    if (localStorage.nn) {
                        listSorder(this.queryParams).then(response => {
                            this.sorderList = response.rows;
                            this.sorderList.forEach(item => {
                                if (item.orderType == 0) {
                                    item.orderType = '补偿';
                                } else if (item.orderType == 1) {
                                    item.orderType = '仅退款';
                                } else {
                                    item.orderType = '退货退款';
                                }
                                //0：已申请，1：审核拒绝，2：已取消, 3: 已完成，4 审核通过待发货，5，待收货
                                if (item.orderStatus == 0) {
                                    item.orderStatus = '待审核';
                                } else if (item.orderStatus == 1) {
                                    item.orderStatus = '审核拒绝';
                                } else if (item.orderStatus == 2) {
                                    item.orderStatus = '已取消';
                                } else if (item.orderStatus == 3) {
                                    item.orderStatus = '已完成';
                                } else if (item.orderStatus == 4) {
                                    item.orderStatus = '审核通过待发货';
                                } else if (item.orderStatus == 5) {
                                    item.orderStatus = '待收货';
                                } else if (item.orderStatus == 6) {
                                    item.orderStatus = '已收货待确认';
                                }
                            });
                            this.total = response.total;
                            this.loading = false;
                        });
                    } else {
                        // this.$message.error('请添加店铺后，再次尝试。');
                    }
                }
            }, 50);
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: undefined,
                uid: undefined,
                companyName: undefined,
                orderId: undefined,
                orderType: undefined,
                compensate: undefined,
                orderStatus: '0',
                platId: undefined,
                plat: undefined,
                shopId: undefined,
                shop: undefined,
                platOrderId: undefined,
                num: undefined,
                price: undefined,
                syncStatus: '0',
                logisticsCompanyNo: undefined,
                logisticsNo: undefined,
                createdTime: undefined,
                resonse: undefined
            };
            this.resetForm('form');
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm');
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            const temp = [];
            selection.forEach(function(item, index) {
                temp.push(item.id);
                // this.skuNoLists.push(item.skuNo);
            });
            this.orderIdList = temp;
            this.ids = selection.map(item => item.orderId);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
            this.queryParams.sorderId = this.ids.join(',');
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = '添加订单';
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.open = true;
            this.row = row;

            // this.reset();
            // const id = row.id || this.ids;
            // getSorder(id).then(response => {
            //     this.form = response.data;
            //     this.open = true;
            //     this.title = "修改订单";
            // });
        },
        //文件上傳
        fieldBeforeUpload(response, file) {
            this.dialogVisibless = true;
            if (response.code == 200) {
                this.lists = [];
                response.data.forEach(element => {
                    console.log(element.errorFields);
                    this.lists.push(element.errorFields);
                });
                this.hiddens = false;
                this.datas = response.data;
            } else {
                this.hiddens = true;
                this.msg = response.msg;
            }
            this.dealFile = [];
            // importOrder({ file: file }).then(res => {
            //     this.datas = res;
            //     this.ishows = true;
            // });
        },
        update() {
            if (window.navigator.msSaveBlob) {
                // IE以及IE内核的浏览器
                try {
                    window.navigator.msSaveBlob(res, fileName); // res为接口返回数据，这里请求的时候已经处理了，如果没处理需要在此之前自行处理var data = new Blob([res.data]) 注意这里需要是数组形式的,fileName就是下载之后的文件名
                    // window.navigator.msSaveOrOpenBlob(res, fileName);  //此方法类似上面的方法，区别可自行百度
                } catch (e) {
                    console.log(e);
                }
            } else {
                let link = document.createElement('a');
                link.href = process.env.VUE_APP_BASE_API + '/after_sale/exportOrderTemplate';
                // let url = window.URL.createObjectURL(new Blob([res]))
                link.style.display = 'none';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link); // 下载完成移除元素
                window.URL.revokeObjectURL(url); // 释放掉blob对象
            }
            // update().then(res => {
            //     console.log(res);
            // });
        },
        /** 提交按钮 */
        submitForm: function() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    if (this.form.id != undefined) {
                        updateSorder(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess('修改成功');
                                this.open = false;
                                this.getList();
                            } else {
                                this.msgError(response.msg);
                            }
                        });
                    } else {
                        addSorder(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess('新增成功');
                                this.open = false;
                                this.getList();
                            } else {
                                this.msgError(response.msg);
                            }
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$confirm('是否确认删除订单编号为"' + ids + '"的数据项?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(function() {
                    return delSorder(ids);
                })
                .then(() => {
                    this.getList();
                    this.msgSuccess('删除成功');
                })
                .catch(function() {});
        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams;
            const orderIdList = this.orderIdList;
            this.$confirm('是否确认导出订单数据项?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(function() {
                    return exportSorder(queryParams);
                })
                .then(response => {
                    //this.download(response.msg);
                    this.msgSuccess(response.msg);
                })
                .catch(function() {});
        }
    },
    watch: {
        '$store.state.user.shopid': function(newFlag, oldFlag) {
            // 需要执行的代码
            this.queryParams.shopId = this.$store.state.user.shopid;
            this.getList();
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss">
.salesType input {
    width: 255px;
}
.sorder .tableCont {
    display: flex;
}
.sorder .tableCont img {
    width: 60px;
    height: 60px;
    float: left;
}
.sorder .tableCont div {
    float: left;
    flex: 1;
    margin-left: 20px;
}
.sorder .tableCont button {
    display: blo ck;
}
.sorder .sync {
    width: 100%;
    display: flex;
    margin-top: 20px;
}
.sorder .sync > span {
    flex: 1;
    text-align: right;
}
.sorder .sync .input {
    width: 78%;
    margin-left: 10px;
}
.sorder .elbutton {
    display: block;
    height: 20px;
    padding: 0;
}
.sorder .header {
    box-sizing: border-box;
    padding-left: 20px;
}
.sorder .header div {
    line-height: 80px;
}
.sorder .el-upload-list {
    display: none !important;
}
</style>
